// 预加载callback
let _readyCallbacks = [];

/**
 * 加载js
 * @param {*} jsPath js路径
 * @param {*} onload 加载完成回调
 */
function loadJs(jsPath, onload = null) {
    var script = document.createElement('script');
    script.onload = onload
    script.src = jsPath;
    document.body.appendChild(script);
}

/**
 * 加载css
 * @param {*} cssPath
 */
function loadCss(cssPath) {
    var link = document.createElement('link');
    link.type = "text/css";
    link.rel = "stylesheet";
    link.href = cssPath;
    document.body.appendChild(link);
}

/**
 * 加载js
 * @param {*} arr js列表
 * @param {*} onload
 */
function chainLoadJs(arr, onload = null) {
    let loadJsByIndex = (i) => {
        if (i < arr.length) {
            let js = arr[i];
            loadJs(js, () => {
                loadJsByIndex(i + 1);
            })
        } else {
            onload && onload();
        }
    }

    loadJsByIndex(0);
}

function ready(cb) {
    if(!window.$workflow) {
        _readyCallbacks.push(cb);
    } else {
        cb && cb();
    }
}

function load(platform, baseUrl) {
    if (window.$workflow) return;
    _readyCallbacks = [];

    console.log("workflow.load start");

    let time = new Date().getTime();

    // 通过workflow-debug来控制是否加载js时采用时间戳
    // 当有时间戳时，由于每次都是新的Js, 无法给js打断点debug
    if(localStorage && localStorage.getItem("workflow-debug")) {
        time = 0;
    }
    loadCss(`${baseUrl}/fbpm-modeler/libs/workflow/${platform}/dist/style.css?t=${time}`);

    let jsList = [
        `${baseUrl}/fbpm-modeler/libs/workflow/${platform}/dist/workflow.umd.min.lib.js?t=${time}`,
        `${baseUrl}/fbpm-modeler/libs/workflow/${platform}/dist/workflow.umd.min.ui.js?t=${time}`,
        `${baseUrl}/fbpm-modeler/libs/workflow/${platform}/dist/workflow.umd.min.js?t=${time}`,
        `${baseUrl}/fbpm-modeler/libs/workflow/${platform}/dist/workflow.umd.min.load.js?t=${time}`
    ];

    chainLoadJs(jsList, () => {
        console.log("workflow.load completed", window.$workflow);

        // 运行ready方法
        try {
            _readyCallbacks.forEach((cb) => cb && cb());
        } catch (e) {

        } finally {
            _readyCallbacks = [];
        }

    });
}

export default {
    ready: ready,
    loadFromApp(baseUrl = "") {
        load("app", baseUrl);
    },
    loadFromBrowser(baseUrl = "") {
        load("vue", baseUrl);
    }
}
